package com.halflife.comeElectricity.member.rider;

import com.halflife.comeElectricity.admin.DateUtil;
import com.halflife.comeElectricity.basic.datadic.RentType;
import com.halflife.comeElectricity.basic.datadic.RentTypeRepository;
import com.halflife.comeElectricity.orderMng.history.HistoryOrder;
import com.halflife.comeElectricity.orderMng.history.HistoryOrderRepository;
import com.halflife.comeElectricity.orderMng.order.OrderEnum;
import com.halflife.comeElectricity.orderMng.order.OrderRiderController;
import com.halflife.framework.domain.Page;
import com.halflife.framework.excel.ExcelRow;
import com.halflife.framework.excel.ExcelSheet;
import com.halflife.framework.participant.Department;
import com.halflife.framework.participant.DepartmentRepository;
import com.halflife.framework.participant.user.UserView;
import com.halflife.framework.utils.ImageUploadUtil;
import com.halflife.shiro.utils.ShiroUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class RiderAdminController {

    private Logger log = LoggerFactory.getLogger(OrderRiderController.class);
    @Resource
    private RiderRepository riderRepository;
    @Resource
    private HistoryOrderRepository historyOrderRepository;
    @Resource
    private PayLogRepository payLogRepository;
    @Resource
    private DepartmentRepository departmentRepository;

    @RequestMapping(value = "/rider/titleImgeUpload", method = RequestMethod.POST)
    public ResponseEntity<Map<String,Object>> titleImgUpload(HttpServletRequest request, HttpServletResponse response,
                                                             Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            MultipartFile file = multipartRequest.getFile("uploadFile");
            String fileName = ImageUploadUtil.upload(request, file);
//            String imageContextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String imageContextPath = "";
            //拼接回传地址
            imageContextPath = imageContextPath +request.getContextPath()+ "/fileUpload/" + sdf.format(new Date()) + "/" + fileName;

            map.put("SUCESS", true);
            map.put("DATA",imageContextPath);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
    }
    @RequestMapping("/rider/list_excel")
    public void riderToExcel(String riderName, String phone,String companyName,Integer state,String beginDate,String endDate, Page page, HttpServletResponse response,
                        HttpServletRequest request, Model model)throws IOException {
        //推送分页Map参数
        HashMap<String, Object> param = new HashMap();
        UserView user = ShiroUtil.getUserView(request);
        param.put("departmentId", user.getDepartmentId());
        if(riderName!=null && riderName!="")
            param.put("name", riderName);
        if(StringUtils.isNotBlank(phone)){
            param.put("phone", phone);
        }if(StringUtils.isNotBlank(companyName)){
            param.put("companyName", companyName);
        }if(state!=null){
            param.put("state", state);
        }
        StringBuilder endSql = new StringBuilder();
        endSql.append("t.state>-1");
        if (StringUtils.isNotBlank(beginDate)) {
            endSql.append(" and t.createDate>='").append(beginDate).append("'");
        }
        if (StringUtils.isNotBlank(endDate)) {
            endSql.append(" and t.createDate<='").append(endDate).append("'");
        }
        param.put("endSql", endSql.toString());

        //查询列表
        List<Rider> list = riderRepository.selectAll(param);
        Workbook wb = new XSSFWorkbook();
        ExcelSheet sheet = new ExcelSheet(wb);
        ExcelRow row = sheet.createRow();

        row.createCell("Department");
        row.createCell("租用类型");
        row.createCell("姓名");
        row.createCell("联系方式");
        row.createCell("集团名称");
        row.createCell("状态");
        row.createCell("注册时间");
        row.createCell("到期时间");
        row.createCell("备注");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        list.forEach((Rider rider)->{
            ExcelRow row_ = sheet.createRow();
            row_.createCell(rider.getDepartment().getName());
            row_.createCell(rider.getRentTypeObj()!=null?rider.getRentTypeObj().getName():"");
            row_.createCell(rider.getName());
            row_.createCell(rider.getPhone());
            row_.createCell(rider.getCompanyName());
            row_.createCell(rider.getStateStr());
            row_.createCell(rider.getCreateDate());
            if (rider.getEndDate() != null) {
                Date date = new Date(rider.getEndDate());
                row_.createCell(sdf.format(date));
            }else{
                row_.createCell("");
            }

            row_.createCell(rider.getExpirDate());
            row_.createCell(rider.getMemo());
        });
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("骑手.xlsx".getBytes(), "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.close();

    }
    /**
     * 骑手管理 edit by liuj3
     * @param response
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/rider/list")
    public String rider(String riderName, String phone,String companyName,Integer state,String beginDate,String endDate, Page page, HttpServletResponse response,
                        HttpServletRequest request, Model model) {
        //推送分页Map参数
        HashMap<String, Object> param = new HashMap();
        UserView user = ShiroUtil.getUserView(request);
        param.put("departmentId", user.getDepartmentId());
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(param);
        if(riderName!=null && riderName!="")
            param.put("name", riderName);
        if(StringUtils.isNotBlank(phone)){
            param.put("phone", phone);
        }if(StringUtils.isNotBlank(companyName)){
            param.put("companyName", companyName);
        }if(state!=null){
            param.put("state", state);
        }
        StringBuilder endSql = new StringBuilder();
        endSql.append("t.state>-1");
        if (StringUtils.isNotBlank(beginDate)) {
            endSql.append(" and t.createDate>='").append(beginDate).append("'");
        }
        if (StringUtils.isNotBlank(endDate)) {
            endSql.append(" and t.createDate<='").append(endDate).append("'");
        }
        param.put("endSql", endSql.toString());

        // param.put("merchantId", merchant.getId());
        int totalCount = riderRepository.selectCount(param);
        //查询列表
        List<Rider> list = riderRepository.selectListByPage(param);
        //计算总页数
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("phone",phone);
        model.addAttribute("beginDate",beginDate);
        model.addAttribute("endDate",endDate);
        model.addAttribute("companyName",companyName);
        model.addAttribute("state",state);
        model.addAttribute("list",list);
        model.addAttribute("riderName",riderName);
        model.addAttribute("totalCount",totalCount);
        return "rider/list";
    }
    @RequestMapping("/rider/listForCompany")
    public String listForComany(String companyId,String riderName,Integer state,String beginDate,String endDate, String phone, Page page, HttpServletResponse response,
                        HttpServletRequest request, Model model) {

        //推送分页Map参数

        HashMap<String, Object> param = new HashMap();
        UserView user = ShiroUtil.getUserView(request);
        param.put("departmentId", user.getDepartmentId());
        param.put("companyId", companyId);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(param);
        param.put("companyId", companyId);


        if(riderName!=null && riderName!="")
            param.put("name", riderName);
        if(StringUtils.isNotBlank(phone)){
            param.put("phone", phone);
        }if(state!=null){
            param.put("state", state);
        }
        StringBuilder endSql = new StringBuilder();
        endSql.append("t.state>-1");
        if (StringUtils.isNotBlank(beginDate)) {
            endSql.append(" and t.createDate>='").append(beginDate).append("'");
        }
        if (StringUtils.isNotBlank(endDate)) {
            endSql.append(" and t.createDate<='").append(endDate).append("'");
        }
        param.put("endSql", endSql.toString());


        // param.put("merchantId", merchant.getId());
        int totalCount = riderRepository.selectCount(param);
        //查询列表
        List<Rider> list = riderRepository.selectListByPage(param);
        //计算总页数
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("companyId",companyId);

        model.addAttribute("phone",phone);
        model.addAttribute("beginDate",beginDate);
        model.addAttribute("endDate",endDate);
        model.addAttribute("state",state);
        model.addAttribute("list",list);
        model.addAttribute("riderName",riderName);
        model.addAttribute("totalCount",totalCount);

        return "rider/listForCompany";
    }

    /**
     * 骑手领钱管理
     * @param merchartName
     * @param
     * @param dateRangeBe
     * @param dateRangeEn
     * @param pageNo
     * @param pageSize
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/riderAccount/list")
    public String gotoRiderAccountList(Integer status, String merchartName, Integer riderId,
                                       String dateRangeBe, String dateRangeEn, Integer pageNo,
                                       Integer pageSize, HttpServletRequest request,
                                       HttpServletResponse response, Model model) {
        //Merchant merchant  =  ShiroUtil.getMerchant();
        BigDecimal riderAccount;
        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(status!=null)
            param.put("status", status);
        if(dateRangeBe!=null && dateRangeBe!="")
            param.put("dateRangeBe", DateUtil.transForMilliSecondByTim(dateRangeBe));
        if(dateRangeEn!=null && dateRangeEn!="")
            param.put("dateRangeEn",DateUtil.transForMilliSecondByTim(dateRangeEn));
        if(merchartName!=null && merchartName!="")
            param.put("merchartName", merchartName);
        if(riderId!=null)
            param.put("riderId", riderId);
        //计算总额
        HashMap<String, Object> param_ = new HashMap();
        param_.put("riderId", riderId);
        param_.put("status", status);
        if(status== OrderEnum.PAYED.m_orderStatus){
            param_.put("currentPage", (pageNo-1)*pageSize);
            param_.put("pageSize", pageSize);
        }
        if(status== OrderEnum.FINISHED.m_orderStatus || status== OrderEnum.PAYED.m_orderStatus){

            riderAccount = historyOrderRepository.selectRiderAccountOrderByPage(param_);
            model.addAttribute("riderAccount",riderAccount);
        }
        if(status== OrderEnum.PAYED.m_orderStatus) {

            param.put("currentPage", (pageNo - 1) * pageSize);
            param.put("pageSize", pageSize);
           // param.put("merchantId", merchant.getId());
        }
        int totalCount = historyOrderRepository.selectHistoryCountOrderByPage(param);
        //查询列表
        List<HistoryOrder> list = historyOrderRepository.selectHistoryOrderByPage(param);
        //计算总页数
        int totalPage = 0;
        if(status== OrderEnum.PAYED.m_orderStatus) {

            totalPage = totalCount / pageSize;
            if (totalCount % pageSize != 0)
                totalPage++;
        }
        model.addAttribute("dateRangeBe",dateRangeBe);
        model.addAttribute("dateRangeEn",dateRangeEn);
        model.addAttribute("merchartName",merchartName);
        model.addAttribute("riderId",riderId);
        model.addAttribute("list",list);
        model.addAttribute("status",status);
        if(status== OrderEnum.PAYED.m_orderStatus) {
            model.addAttribute("totalPage",totalPage);
            model.addAttribute("pageNo",pageNo);
            model.addAttribute("pageSize",pageSize);
            model.addAttribute("totalCount",totalCount);
        }
        return "merchant/rider/accountlist";
    }


    @RequestMapping("/rider_orderAccount/account")
    public ResponseEntity getAccountbyIds(String ids, HttpServletRequest request,
                                          HttpServletResponse response, Model model) {
        try{

            BigDecimal totalCount;
            HashMap<String, Object> param = new HashMap();
            List<String> list = new ArrayList<String>();
            if(ids!=null&&ids!=""){

                String[] l = ids.split(",");
                for(String i : l){
                    if(i!=null&i!="")
                        list.add(i);
                }
                param.put("ids",list);
                totalCount = historyOrderRepository.selectOrderAccountSumByIds(param);
                return new ResponseEntity(totalCount, HttpStatus.OK);
            }else
                return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        } catch (Exception e) {

            log.error(e.getMessage(), e);
            return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        }
    }

    @RequestMapping("/rider/setState")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            Rider rider = new Rider();
            rider.setId(id);
            rider.setState(state);
            riderRepository.updateByPrimaryKeySelective(rider);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
    @RequestMapping("/rider/savePayLogMemo")
    public ResponseEntity savePayLogMemo(Integer id, String memo) {
        try {
            PayLog updatePayLog = new PayLog();
            updatePayLog.setId(id);
            updatePayLog.setMemo(memo);
            payLogRepository.updateByPrimaryKeySelective(updatePayLog);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @RequestMapping("/rider_orderAccount/update")
    public ResponseEntity updateAccountbyIds(String ids, String memo, String riderId, HttpServletRequest request,
                                             HttpServletResponse response, Model model) {
        try{

            BigDecimal totalCount;
            HashMap<String, Object> param = new HashMap();
            List<String> list = new ArrayList<String>();
            if(ids!=null&&ids!=""){

                String[] l = ids.split(",");
                for(String i : l){
                    if(i!=null&i!="")
                        list.add(i);
                }
                param.put("ids",list);
                totalCount = historyOrderRepository.selectOrderAccountSumByIds(param);
                //更新订单状态
                param.put("status",OrderEnum.PAYED.m_orderStatus);
                historyOrderRepository.updateOrderStatus(param);
                //生成付款记录
                PayLog log = new PayLog();
                log.setRiderId(Integer.parseInt(riderId));
                log.setPayMoney(totalCount);
                log.setMemo(memo);
                log.setCreateDate(Calendar.getInstance().getTimeInMillis());
                payLogRepository.insert(log);
                return new ResponseEntity(1, HttpStatus.OK);
            }else
                return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        } catch (Exception e) {

            log.error(e.getMessage(), e);
            return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        }
    }

    @Resource
    private RentTypeRepository rentTypeRepositoty;

    @RequestMapping("/rider/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                              HttpServletRequest request, Model model) {
        HashMap queryParam = new HashMap();
        queryParam.put("valid", true);
        queryParam.put("orderSql", "t.ordinal");
        List<Department> departmentList = departmentRepository.selectAll(queryParam);
        Rider rider = new Rider();
        if(id!=null){
            rider = riderRepository.selectByPrimaryKey(id);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("valie", true);
        List<RentType> rentTypeList = rentTypeRepositoty.selectAll(param);
        model.addAttribute("rentTypeList",rentTypeList);
        model.addAttribute("rider",rider);
        model.addAttribute("departmentList",departmentList);
        return "rider/operate";
    }

    @RequestMapping("/rider/operateForCompany")
    public String gotoOperateForCompany(Integer companyId,Integer id,HttpServletResponse response,
                              HttpServletRequest request, Model model) {
        Rider rider = new Rider();
        if(id!=null){
            rider = riderRepository.selectByPrimaryKey(id);
        }
        rider.setCompanyId(companyId);
        model.addAttribute("rider",rider);
        model.addAttribute("companyId",companyId);
        return "rider/operateForCompany";
    }

    @PostMapping("/rider/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(Rider rider, HttpServletRequest request,
                               HttpServletResponse response, Model model) {
        try {
            if(rider.getId()!=null){
                if (StringUtils.isNotBlank(rider.getExpirDate())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    long time = sdf.parse(rider.getExpirDate()).getTime();
                    rider.setEndDate(time);
                }
                if (StringUtils.isNotBlank(rider.getExpirJhDate())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    long time = sdf.parse(rider.getExpirJhDate()).getTime();
                    rider.setJhDate(time);
                }
                riderRepository.updateByPrimaryKeySelective(rider);
                if (rider.getState() == 0) {
                    rider = riderRepository.selectByPrimaryKey(rider.getId());
                    rider.setEndDate(new Date().getTime());
                    rider.setCompanyName(null);
                    rider.setCompanyId(null);
                    rider.setJhDate(null);
                    riderRepository.updateByPrimaryKey(rider);
                }
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
    @PostMapping("/rider/saveForCompany")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity saveForCompany(Integer companyId,Rider rider, HttpServletRequest request,
                               HttpServletResponse response, Model model) {
        try {
            if(rider.getId()!=null){
                riderRepository.updateByPrimaryKeySelective(rider);
            }else{
                UserView user = ShiroUtil.getUserView(request);
                rider.setDepartmentId(user.getDepartmentId());
                rider.setState(RiderStatus.NORMAL.getValue());
                riderRepository.insert(rider);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
